package org.finesys.quartz.support;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.finesys.common.quartz.core.constants.JobExecuteStatusEnum;
import org.finesys.common.quartz.core.exception.TaskException;
import org.finesys.quartz.convert.SysJobConvert;
import org.finesys.quartz.entity.SysJob;
import org.finesys.quartz.entity.SysJobLog;
import org.finesys.quartz.event.SysJobLogEvent;
import org.finesys.quartz.service.SysJobService;
import org.quartz.CronTrigger;
import org.quartz.JobExecutionContext;
import org.quartz.Trigger;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.ZoneId;
import java.util.Date;

@Component
@Slf4j
@RequiredArgsConstructor
public class TaskInvokeUtil {

    private final SysJobService sysJobService;
    private final ApplicationEventPublisher applicationEventPublisher;

    public void invoke(SysJob sysJob, JobExecutionContext context) {
        //开始时间
        long startTime = System.currentTimeMillis();
        //转换日志对象
        SysJobLog sysJobLog = SysJobConvert.INSTANCE.convert(sysJob);
        //更新定时任务对象
        SysJob updateSysJob = new SysJob();
        updateSysJob.setJobId(sysJob.getJobId());
        //执行任务
        TaskInvokeService taskInvokeService = TaskInvokeServiceFactory.taskInvokeService(sysJob.getJobType());
        if (ObjectUtils.isEmpty(taskInvokeService)) {
            sysJobLog.setJobLogStatus(JobExecuteStatusEnum.FAILUER.getValue());
            sysJobLog.setJobMessage(JobExecuteStatusEnum.FAILUER.getRemark() + ",未找到TaskInvoce服务类");
            applicationEventPublisher.publishEvent(new SysJobLogEvent(this, sysJobLog));
            return;
        }
        try {
            taskInvokeService.invoke(sysJob);
            updateSysJob.setJobExecuteStatus(JobExecuteStatusEnum.SUCCESS.getValue());
            sysJobLog.setJobLogStatus(JobExecuteStatusEnum.SUCCESS.getValue());
            sysJobLog.setJobMessage(JobExecuteStatusEnum.SUCCESS.getRemark());
        } catch (TaskException e) {
            log.error("定时任务执行失败，任务名称：{}；任务组名：{}，cron执行表达式：{}，执行时间：{}", sysJob.getJobName(), sysJob.getJobGroup(),
                    sysJob.getCronExpression(), new Date());
            // 记录失败状态
            sysJobLog.setJobMessage(JobExecuteStatusEnum.FAILUER.getRemark());
            sysJobLog.setJobLogStatus(JobExecuteStatusEnum.FAILUER.getValue());
            sysJobLog.setExceptionInfo(StrUtil.sub(e.getMessage(), 0, 2000));
            // 任务表信息更新
            updateSysJob.setJobExecuteStatus(JobExecuteStatusEnum.FAILUER.getValue());
        } finally {
            Trigger trigger = context.getTrigger();
            // 记录执行时间 立刻执行使用的是simpleTeigger
            if (trigger instanceof CronTrigger) {
                updateSysJob.setStartTime(trigger.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                updateSysJob.setPreviousTime(
                        trigger.getPreviousFireTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                updateSysJob.setNextTime(
                        trigger.getNextFireTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
            }
            // 记录执行时长
            long endTime = System.currentTimeMillis();
            sysJobLog.setExecuteTime(String.valueOf(endTime - startTime));

            applicationEventPublisher.publishEvent(new SysJobLogEvent(this, sysJobLog));
            sysJobService.updateById(updateSysJob);
        }


    }
}
